package com.ropa.java;

import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.IntStream;

public class ForkJoinPollDemo {
    public static void main(String[] args) {
        manual();
//        executors();
    }

    /**
     * 手动创建
     */
    private static void manual() {
        ForkJoinPool forkJoinPool = new ForkJoinPool(2);
        forkJoinPool.submit(() -> {
            IntStream.range(1,99999999).parallel()
                    .forEach(i-> System.out.printf("thread: %s , i: %d %n",Thread.currentThread().getId(),i));
        });

        try {
            forkJoinPool.awaitTermination(100, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过 Executors 创建
     */

    private static void executors() {
        ExecutorService executorService = Executors.newWorkStealingPool(2);

        int t = 10;

        for (int i = 0; i < 8; i++) {
            executorService.submit(new PseudoTimeAction(t - i));
        }

        try {
            executorService.awaitTermination(20, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    static class PseudoTimeAction implements Runnable {

        public PseudoTimeAction(int sleepSeconds) {
            this.sleepSeconds = sleepSeconds;
        }

        private String name = RandomUtil.randomString(4);

        private int sleepSeconds;

        @Override
        public void run() {
            System.out.println("start action :" + name);
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
            System.out.println("end action : " + name);
        }
    }
}


